package me.itsoo.artemis.framework.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

/**
 * ClassPathFileResource
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/6/5
 */
public class ClassPathFileResource implements Resource {

    private final String filePath;

    private URL fileResource;

    private boolean isFile;

    public ClassPathFileResource(String filePath) {
        this.filePath = filePath;

        init();
    }

    private void init() {
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            fileResource = classLoader.getResource(filePath);
            isFile = true;
        } catch (Exception e) {
            isFile = false;
        }
    }

    @Override
    public boolean isFile() {
        return isFile;
    }

    @Override
    public String[] getFilenames() {
        return new String[]{filePath};
    }

    @Override
    public void loadProperties(Properties properties) {
        if (Objects.nonNull(fileResource)) {
            try (InputStream is = fileResource.openStream()) {
                properties.load(is);
            } catch (IOException ignore) { // NOSONAR
            }
        }
    }
}
